package com.example.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 
* @ClassName: HttpAspect 
* @Description: TODO(用于拦截http请求) 
* @author 强哥 
* @date 2017年12月12日 下午3:16:35 
*
 */
@Aspect
@Component
public class HttpAspect {
	private final static Logger logger=LoggerFactory.getLogger(HttpAspect.class);
	
//	@Before("execution(public * com.example.controller..*(..))")
//	public void log(){
//		System.out.println(111111);
//	}
	//定义切面
	@Pointcut("execution(public * com.example.controller..*(..))")
	public void log(){}
	
	
	@Before("log()")//log()为切面方法名
	public void doBefore(JoinPoint joinpoint){
//		System.out.println(111111);
//		logger.info("111111");
		ServletRequestAttributes attributes=
				(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request= attributes.getRequest();
		
		
		
//		url
		logger.info("url={}",request.getRequestURL());
//		method
		logger.info("method={}",request.getMethod());
//		ip
		logger.info("ip={}",request.getRemoteAddr());
//		类方法
		logger.info("class_method={}",joinpoint.getSignature().getDeclaringTypeName()+"."
				+joinpoint.getSignature().getName());
//		参数
		logger.info("args={}",joinpoint.getArgs());
		
	}
	
	@After("log()")
	public void doAfter(){
//		System.out.println(222222);
		logger.error("HttpAspect:doAfter()");
	}
	
	@AfterReturning(returning="object", pointcut="log()")
	public void doAfterReturning(Object object){
		logger.info("response={}",object.toString());
	}
	
}
